#!/usr/bin/env python
#encoding: utf-8
import ia_configure
import urllib2
from urllib2 import URLError, HTTPError
import json
import sys
reload(sys)
sys.setdefaultencoding('utf8')


class py_http():

    def __init__(self):
        pass

    def http_read(self,s_url,s_header,s_timeout,s_data=''):
        if s_data=='':
            req = urllib2.Request(url=s_url,headers=s_header)
        else:
            req = urllib2.Request(url=s_url,data=s_data,headers=s_header)

        try:
            response = urllib2.urlopen(req,timeout=s_timeout)
            the_page = response.read()
            return the_page

        except HTTPError,e:
            return e.read()

        except URLError,e:
            return self.Cjson('URLError '+str(e.reason))
        except:
            return self.Cjson('http_read other error or time out')

    def Cjson(self,text):
        b={}
        b['errcode']=8888
        b['errmsg']=text
        return json.dumps(b,encoding="UTF-8",ensure_ascii=False)

class weixin_msg():
    def __init__(self):
        self.token=''
        self.surl=''
        self.CorpID=ia_configure.CorpID
        self.Secret=ia_configure.Secret
        pytp=py_http()
        jdata=pytp.http_read('https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='+self.CorpID+'&corpsecret='+self.Secret,{},10)
        self.token=json.loads(jdata)['access_token']
        self.surl='https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token='+self.token

    def wx_Msg_txt(self,surl,totype,toId,agentid,content,msgtype='text'):
        pytp=py_http()
        msg_text={}
        msg_t={}
        if totype=='touser':
            msg_text['touser']=toId
        elif totype=='toparty':
            msg_text['toparty']=toId
        msg_text['msgtype']=msgtype
        msg_text['agentid']=agentid
        #msg_t={'content':content}
        msg_t['content']=content
        msg_text['text']=msg_t
        jdata=json.dumps(msg_text,encoding="utf-8",ensure_ascii=False)
        redata=json.loads(pytp.http_read(self.surl,{},10,jdata))
        return redata


if __name__ == '__main__':
    #save_auth(get_token())
    a=weixin_msg()
    print a.wx_Msg_txt(a.surl,'toparty',ia_configure.id_txl_qa,ia_configure.id_app_jiekou,'测试')